package cc.facesign.admin.service.impl;

import cc.facesign.admin.bean.TblManageDept;
import cc.facesign.admin.mapper.TblManageDeptMapper;
import cc.facesign.admin.service.AclService;
import cc.facesign.admin.service.TblDeptService;
import cc.facesign.admin.service.TblManageDeptService;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.type.RoleType;
import cc.facesign.common.utils.bean.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-05-06
 */
@Service
@Transactional
public class TblManageDeptServiceImpl extends ServiceImpl<TblManageDeptMapper, TblManageDept> implements TblManageDeptService {

    @Autowired
    private AclService aclService;

    @Autowired
    private TblDeptService deptService;

    @Override
    public void setManage(String deptId, String userId) {
        TblManageDept manageDept = new TblManageDept();
        manageDept.setDeptId(deptId);
        manageDept.setUserId(userId);

        QueryWrapper<TblManageDept> w = new QueryWrapper<>();
        w.eq("dept_id", deptId);
        w.eq("user_id", userId);
        if (count(w) == 0) save(manageDept);
    }

    @Override
    public int countForManager(String deptId) {
        QueryWrapper<TblManageDept> w = new QueryWrapper<>();
        w.eq("dept_id", deptId);
        return count(w);
    }

    @Override
    public void deleteManager(String deptId, String userId) {
        int count = countForManager(deptId);
        if (count == 1) { //  必然有单位创始人
            throw new FacesignException(R.ERROR, "该部门不能没有管理者");
        }

        baseMapper.deleteRelate(deptId, userId);
    }

    @Override
    public int deleteManagerForce(String deptId, String rid) {
        QueryWrapper<TblManageDept> w = new QueryWrapper<>();
        w.eq("dept_id", deptId);

        List<String> ids = list(w).stream()
                .map(x -> x.getUserId())
                .collect(Collectors.toList());

        int count = baseMapper.deleteManagerForce(deptId);

        for (String id : ids) {
            aclService.deleteManage(id, rid, RoleType.DEPT);
        }

        return count;

    }

    @Override
    public String getRManageId(String deptId) {
        String rid = deptService.getRid(deptId);
        QueryWrapper<TblManageDept> w = new QueryWrapper<>();
        w.eq("dept_id", rid);
        return getOne(w).getUserId();
    }
}
